package com.zking.dao;

import com.zking.dao.NewsDao;
import com.zking.entity.News;
import com.zking.util.DBUtil;

import java.util.List;

public class NewsDao {
    public static List<News> getNewsByPage(int pageIndex, int pageSize) {
        String sql = "select * from easybuy_news limit ?,?";
        return DBUtil.query(sql, News.class, (pageIndex-1)*pageSize,pageSize);
    }

    public static int getMaxPage(int pageSize) {
        List<News> list = getAllNews();
        int total = list.size();
        int maxPage = total/pageSize;
        if(total%pageSize!=0){
            maxPage++;
        }
        return maxPage;
    }

    public static List<News> getAllNews() {
        String sql = "select * from easybuy_news";
        return DBUtil.query(sql, News.class);
    }

    public static boolean addNews(News news) {
        String sql = "insert into easybuy_news values(null,?,?,now())";
        return DBUtil.update(sql,news.getEn_title(),news.getEn_content());
    }

    public static boolean deleteNews(int en_id) {
        String sql = "delete from easybuy_news where en_id=?";
        return DBUtil.update(sql,en_id);
    }

    public static News getNewsById(int en_id) {
        String sql = "select * from easybuy_news where en_id=?";
        List<News> list = DBUtil.query(sql, News.class,en_id);
        if(list.size()==1){
            return list.get(0);
        }
        return null;
    }

    public static boolean updateNews(News news) {
        String sql = "update easybuy_news set en_title=?,en_content=? where en_id=?";
        return DBUtil.update(sql,news.getEn_title(),news.getEn_content(),news.getEn_id());
    }
}
